<!--
*  2021-03-15
*  余纱退回
-->
<template>
  <div id="app" class="yarn-list" tabindex="-1" ref="tabDiv">
    <!-- 头部导航 -->
    <van-nav-bar
      left-arrow
      title="余纱退回"
      left-text="返回"
      @click-left="onClickLeft"
    >
      <template #right>
        <van-search v-model="query" clearable placeholder="请输入搜索关键词" />
        <van-button type="info" @click="onClickRight">新 增</van-button>
      </template>
    </van-nav-bar>
    <!-- 确认信息 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group>
        <van-cell>
          <template slot="title">
            <div class="yarn-cell">
              <span>ID</span>
              <span>规格</span>
              <span>颜色</span>
              <span>批次</span>
              <span>标重</span>
              <span>时间</span>
            </div>
          </template>
          <template slot="default">
            <span>操作</span>
          </template>
        </van-cell>
        <van-cell v-for="(data, index) in tableData" :key="index">
          <template slot="title">
            <div class="yarn-cell">
              <span>{{ data.id }}</span>
              <span>{{ data.standardNo }}</span>
              <span>{{ data.colorName + data.standard }}</span>
              <span>{{ data.lotNum }}</span>
              <span>{{ data.weight }}</span>
              <span>{{ data.updateAt }}</span>
            </div>
          </template>
          <template slot="default">
            <van-button
              @click="onClickPrint(data)"
              type="danger"
              style="margin-right: 10px"
              >打 印</van-button
            >
            <van-button type="danger" @click="onClickDrop(data, index)"
              >废弃</van-button
            >
          </template>
        </van-cell>
      </van-cell-group>
    </better-scroll>
    <van-pagination
      v-if="totalRow != 0"
      v-model="currentPage"
      :total-items="totalRow"
      :items-per-page="10"
      force-ellipses
    />

    <van-dialog
      v-model="show"
      title="余纱退回"
      className="yarn-list-dialog"
      showCancelButton
      :before-close="onBeforeClose"
      @confirm="onConfirm"
      @cancel="onCancelBtn"
      :style="{ top: top }"
    >
      <van-cell
        title="编号："
        is-link
        :value="no"
        @click="onClickFocus"
      ></van-cell>
      <van-cell title="名称：" :value="name + standardName"></van-cell>
      <van-cell title="批次号：">
        <template slot="default">
          <van-field v-model="lotNum" placeholder="请输入" />
        </template>
      </van-cell>
      <van-cell title="筒只数：">
        <template slot="default">
          <van-field v-model="spindleNum" type="tel" placeholder="请输入" />
        </template>
      </van-cell>
      <van-cell
        title="筒材质："
        :value="spindleMaterialName"
        is-link
        @click="onClickDialog"
      ></van-cell>
      <van-cell
        title="筒管颜色："
        :value="spindleColor"
        is-link
        @click="onClickShow"
      ></van-cell>

      <van-cell title="毛重：">
        <template slot="default">
          <van-field
            v-model="grossWeight"
            type="tel"
            placeholder="请输入"
            ref="refInput"
            @blur="onClickBlur"
            @focus="onGetWeight"
            @keyup.enter.native="onClickSubmit"
          />
        </template>
      </van-cell>
      <van-cell title="净重：">
        <template slot="default">
          <van-field
            v-model="netWeight"
            type="tel"
            placeholder="请输入"
            @blur="onClickBlur"
            @focus="onChangeTop(2)"
          />
        </template>
      </van-cell>
      <van-cell title="标重：">
        <template slot="default">
          <van-field
            v-model="weight"
            type="tel"
            placeholder="请输入"
            @blur="onClickBlur"
            @focus="onChangeTop(3)"
          />
        </template>
      </van-cell>
    </van-dialog>

    <!-- 筒管材质 -->
    <van-action-sheet
      v-model="isDialog"
      :actions="spindleMaterialOptions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelectMaterial"
      @close="onClickClose"
    />
    <!-- 筒管颜色 -->
    <van-action-sheet
      v-model="isShow"
      :actions="actions"
      close-on-click-action
      @select="onSelectColor"
      @close="onClickClose"
    />
    <!-- 编号 -->
    <van-popup
      v-model="showPicker"
      position="bottom"
      style="height: 70%"
      @close="onClickClose"
    >
      <van-picker
        show-toolbar
        value-key="no"
        :columns="columns"
        @confirm="onConfirmNo"
        @cancel="onCancel"
      >
        <template slot="title">
          <van-search
            v-model="keyLike"
            placeholder="请输入搜索关键词"
            @search="onGetYarnStandardList"
          />
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
import {
  getWeavingYarnBack,
  getYarnPackageAdd,
  getYarnPackageDrop,
  getYarnStandardFilter,
  getSpindleColor,
  getYarnPackageFilter,
} from "@/api/warping";
import { getInit, getRefreshToken } from "@/api/login";
import { openWin, getFloat } from "@/utils/index";
import { getInfo, setInfo } from "@/utils/auth";
import dayjs from "dayjs";
export default {
  name: "yarn",
  data() {
    return {
      tableData: [],
      show: false,
      totalPage: 1,
      spindleNum: "",
      lotNum: "",
      modulus: "",
      spindleMaterial: 1,
      spindleMaterialName: "塑料",
      spindleColor: "米黄",
      grossWeight: "",
      netWeight: "",
      weight: "",
      yarnStrandNum: "",
      yarnStandard: "",
      colorName: "",
      yarnName: "",
      stdMoistureRegain: "",
      isShow: false,
      actions: [],
      isDialog: false,
      spindleMaterialOptions: [
        { name: "塑料", value: 1 },
        { name: "纸质", value: 2 },
      ],
      showStatus: false,
      showPicker: false,
      columns: [],
      no: "请选择",
      name: "",
      timeout: null,
      keyLike: "",
      standardName: "",
      batchName: "",
      query: "",
      currentPage: 1,
      totalRow: 0,
      scrollH: 350,
      top: 350,
      lock: false,
      timer: null,
      filedInputLock: false,
      printRow: {},
    };
  },
  watch: {
    // 监听编号
    query(oldVal, newVal) {
      // 防止input连续输入时，频繁发请求
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // 筛选
        if (oldVal !== newVal) {
          this.currentPage = 1;
          this.onGetTableData();
        }
      }, 3000);
    },
    currentPage() {
      this.onGetTableData();
    },
    grossWeight(newVal) {
      if (!this.lock) {
        if (newVal) {
          this.netWeight = getFloat(
            newVal - 0.1 - (this.spindleMaterial === 1 ? 0.075 : 0.05),
            1
          );
        }
        if (newVal && this.modulus) {
          let spindleMaterialVal = this.spindleMaterial === 1 ? 0.075 : 0.05;
          this.weight = getFloat(
            ((this.grossWeight - 0.1 - this.spindleNum * spindleMaterialVal) *
              (1 + this.stdMoistureRegain / 100)) /
              (1 + this.modulus / 100),
            1
          );
        }
      }
    },
    spindleNum() {
      if (this.grossWeight && this.modulus && !this.lock) {
        let spindleMaterialVal = this.spindleMaterial === 1 ? 0.075 : 0.05;
        this.weight = getFloat(
          ((this.grossWeight - 0.1 - this.spindleNum * spindleMaterialVal) *
            (1 + this.stdMoistureRegain / 100)) /
            (1 + this.modulus / 100),
          1
        );
      }
    },
    spindleMaterial() {
      if (this.spindleMaterial == 1) {
        this.spindleColor = "米黄";
        this.onGetSpindleColor();
      } else {
        this.spindleColor = "本白";
        this.actions = [
          { name: "本白", value: "本白" },
          { name: "红头", value: "红头" },
          { name: "兰头", value: "兰头" },
          { name: "绿头", value: "绿头" },
          { name: "黑头", value: "黑头" },
        ];
      }
      if (this.spindleMaterial != "" && !this.lock) {
        this.netWeight = getFloat(
          this.grossWeight - 0.1 - (this.spindleMaterial === 1 ? 0.075 : 0.05),
          1
        );
      }
      if (this.grossWeight && this.modulus && !this.lock) {
        let spindleMaterialVal = this.spindleMaterial === 1 ? 0.075 : 0.05;
        this.weight = getFloat(
          ((this.grossWeight - 0.1 - this.spindleNum * spindleMaterialVal) *
            (1 + this.stdMoistureRegain / 100)) /
            (1 + this.modulus / 100),
          1
        );
      }
    },
    modulus() {
      if (this.grossWeight && this.modulus && !this.lock) {
        let spindleMaterialVal = this.spindleMaterial === 1 ? 0.075 : 0.05;
        this.weight = getFloat(
          ((this.grossWeight - 0.1 - this.spindleNum * spindleMaterialVal) *
            (1 + this.stdMoistureRegain / 100)) /
            (1 + this.modulus / 100),
          1
        );
      }
    },
    // 监听编号
    // keyLike(oldVal, newVal) {
    //   if (newVal && !this.showStatus) {
    //     // 防止input连续输入时，频繁发请求
    //     clearTimeout(this.timeout);
    //     this.timeout = setTimeout(() => {
    //       // 筛选
    //       if (oldVal !== newVal) {
    //         this.onGetYarnStandardList();
    //       }
    //     }, 1500);
    //   }
    // },
    // 监听打印机mac
    printMac(newVal) {
      if (newVal) {
        this.connectBleByMacAddress();
      }
    },
    show() {
      if (!this.show) {
        this.lock = false;
        this.onGetSpindleColor();
        this.onGetTableData();
        this.onWatchEnter();
      }
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        // 获取确认信息
        that.onGetInit();
        that.onGetSpindleColor();
        that.onGetTableData();
        that.onWatchEnter();
        that.timer = setInterval(() => {
          that.onGetRefreshToken();
        }, 1500000);
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            window.removeEventListener("keydown", that.onClickKeydown);
            window.api.closeWin();
          }
        );
      });
    } else {
      window.apiready = () => {
        // 获取确认信息
        // that.onGetInit();
        that.onGetSpindleColor();
        that.onGetTableData();
        that.onWatchEnter();
        that.timer = setInterval(() => {
          that.onGetRefreshToken();
        }, 1500000);
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            window.removeEventListener("keydown", that.onClickKeydown);
            window.api.closeWin();
          }
        );
      };
    }
  },
  methods: {
    // 刷新token
    onGetRefreshToken() {
      getRefreshToken(
        {
          secret: getInfo().secret,
        },
        (res) => {
          setInfo(res);
        }
      );
    },
    destroyed() {
      clearInterval(this.timer);
    },
    // 返回
    onClickLeft() {
      openWin("index");
    },
    // 新增打包
    onClickRight() {
      this.show = true;
    },
    // 废弃操作
    onClickDrop(data, index) {
      const that = this;
      getYarnPackageDrop(data.id, () => {
        that.$toast({
          type: "success",
          message: "废弃成功",
          onClose: () => {
            that.tableData.splice(index, 1);
          },
        });
      });
    },
    // 打印初始化
    onGetInit() {
      this.printMac = "";
      getInit({}, (res) => {
        let resultArr = eval("(" + res.propertyValue + ")");
        resultArr.forEach((item) => {
          if (item.type == "1") {
            this.printMac = item.mac;
          }
        });
      });
    },
    // 点击打印
    onClickPrint(row) {
      this.printStatus = true;
      this.printRow = row;
      if (this.printMac) {
        this.getConnectState();
      } else {
        // 初始化
        this.onGetInit();
      }
    },

    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        type: "loading",
        message: "查询打印机连接状态",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          that.$toast({
            type: "success",
            message: that.printStatus ? "已连接,正在打印" : "已连接",
            duration: 1500,
            onClose: () => {
              // 打印
              if (that.printStatus) {
                that.printLabel();
              }
            },
          });
        } else {
          // 未连接
          that.$toast.clear();
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast.clear();
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // mac 地址连接
    connectBleByMacAddress() {
      const that = this;
      that.$toast({
        type: "loading",
        message: "初始化",
        duration: 20000,
      });
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress:
            process.env.NODE_ENV === "production"
              ? that.printMac
              : "DC:1D:30:C6:A2:E4",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.$toast.clear();
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
                onClose: () => {
                  if (that.printStatus) {
                    that.printLabel();
                  }
                },
              });
            } else if (ret.message === "连接失败") {
              that.$toast.clear();
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            }
          } else {
            that.$toast.clear();
            that.$toast.fail(err.msg);
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              // 图片单元格竖线
              lineType: "bar",
              x: 25 + 130,
              y: 0,
              width: 2,
              height: 136,
            },
            {
              //绘制图片
              lineType: "image",
              x: 25 + 8,
              y: 8,
              data: "widget://image/huibo_logo.png",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 10,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: "艺多染整",
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 25 + 170 + 2,
              y: 10,
              level: "L", //L|M|H|Q
              cellwith: 5,
              rotation: 0, // 0|90|180|270
              data:
                "{" +
                "Id:" +
                "'" +
                that.printRow.id +
                "," +
                that.printRow.standardId +
                "'" +
                "}",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 86 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "余纱退回",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 36 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: that.printRow.id,
            },
            {
              // 横线
              lineType: "bar",
              x: 25 + 4,
              y: 136,
              width: 156,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: dayjs().format("YYYY-MM-DD"),
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 200 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "批次号：" + that.printRow.lotNum,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 186,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 186 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "编号：" + that.printRow.standardNo,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 236,
              width: 608,
              height: 2,
            },
            // {
            //   //绘制文本
            //   lineType: "text",
            //   x: 25 + 4,
            //   y: 236 + 2,
            //   rotation: 0,
            //   xscal: 1,
            //   yscal: 2,
            //   data: "批次号：" + that.printRow.lotNum,
            // },
            // {
            //   // 横线
            //   lineType: "bar",
            //   x: 25,
            //   y: 286,
            //   width: 608,
            //   height: 2,
            // },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 286 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "颜色：" + that.printRow.colorName + that.printRow.standard,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 336,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 336 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "毛重：" + that.printRow.grossWeight,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 386,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 386 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "净重：" + that.printRow.netWeight,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 436,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "回潮: " + that.printRow.modulus,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 150 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "筒只数: " + that.printRow.spindleNum,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 486,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 486 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "标重: " + that.printRow.weight,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 150 + 4,
              y: 486 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "筒只颜色: " + that.printRow.spindleColor,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 536,
              width: 600,
              height: 2,
            },
            // {
            //   //绘制文本
            //   lineType: "text",
            //   x: 25 + 4,
            //   y: 506 + 2,
            //   rotation: 0,
            //   xscal: 1,
            //   yscal: 2,
            //   data: "日期: " + dayjs().format("YYYY-MM-DD"),
            // },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.printStatus = false;

            // that.printRow = {};
            // that.yarnId = ''
            // that.no = ''
            // that.name = ''
            // that.standardName = ''
            // that.batchName = ''
            // that.batchName = ''
            // that.spindleMaterial = 1
            // that.spindleMaterialName = "塑料"
            // that.spindleColor = "米黄",
            // that.spindleNum = ''
            // that.grossWeight = ''
            // that.netWeight = ''
            // that.weight = ''
            // that.modulus = ''
            // that.stdMoistureRegain = ''
            that.onWatchEnter();
            that.$toast.success("打印成功");
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
    onGetSpindleColor() {
      this.actions = [];
      getSpindleColor({}, (res) => {
        res.forEach((item) => {
          let params = {};
          params.name = item.propertyName;
          params.value = item.propertyName;
          this.actions.push(params);
        });
      });
    },
    onClickFocus() {
      this.showStatus = false;
      this.showPicker = true;
      this.keyLike = "";
      this.filedInputLock = true;
      this.onGetYarnStandardList();
    },
    onClickDialog() {
      this.isDialog = true;
      this.filedInputLock = true;
    },
    onClickShow() {
      this.isShow = true;
      this.filedInputLock = true;
    },
    onClickClose() {
      this.filedInputLock = false;
    },
    // 获取编号
    onGetYarnStandardList() {
      this.columns = [];

      getYarnStandardFilter(
        {
          standard: this.keyLike,
        },
        (res) => {
          if (res.code) {
            this.$toast.fail("筛选无数据");
          } else {
            this.$refs.tabDiv.focus();
            res.forEach((item) => {
              let params = {};
              params.no = item.no;
              params.yarnId = item.id;
              params.name = item.colorName;
              params.stdMoistureRegain = item.stdMoistureRegain;
              params.actMoistureRegain = item.actMoistureRegain;
              params.colorName = item.colorName;
              params.standardName = item.standard + "/" + item.strandNum;
              params.batchName = item.name;
              this.columns.push(params);
            });
          }
        }
      );
    },
    // 确认编号
    onConfirmNo(val) {
      this.showStatus = true;
      this.no = val.no;
      this.yarnId = val.yarnId;
      this.name = val.colorName;
      this.modulus = val.actMoistureRegain;
      this.stdMoistureRegain = val.stdMoistureRegain;
      this.standardName = val.standardName;
      this.batchName = val.batchName;
      this.showPicker = false;
      this.filedInputLock = false;
    },
    onCancel() {
      this.showPicker = false;
      this.filedInputLock = false;
    },
    onCancelBtn() {
      this.show = false;
    },
    onBeforeClose(action, done) {
      if (action === "confirm") {
        return done(false);
      } else {
        return done();
      }
    },
    // 新增保存
    onConfirm() {
      this.printStatus = false;
      if (this.printMac) {
        getYarnPackageAdd(
          {
            standardId: this.yarnId,
            grossWeight: this.grossWeight,
            weight: this.weight,
            netWeight: this.netWeight,
            modulus: this.modulus,
            spindleNum: this.spindleNum,
            spindleMaterial: this.spindleMaterial,
            spindleColor: this.spindleColor,
            lotNum: this.lotNum,
            type: 2,
            refType: 11,
          },
          (res) => {
            this.lock = false;
            this.printStatus = true;
            this.printRow = {
              id: res,
              standardId: this.yarnId,
              standardNo: this.no,
              standardName: this.batchName,
              colorName: this.name,
              standard: this.standardName,
              grossWeight: this.grossWeight,
              netWeight: this.netWeight,
              modulus: this.modulus,
              spindleNum: this.spindleNum,
              weight: this.weight,
              lotNum: this.lotNum,
              spindleColor: this.spindleColor,
            };
            this.getConnectState();
            window.removeEventListener("keydown", this.onClickKeydown);
          }
        );
      } else {
        // 初始化
        this.onGetInit();
      }
    },
    // 选择筒管材质
    onSelectMaterial(data) {
      this.spindleMaterialName = data.name;
      this.spindleMaterial = data.value;
    },
    // 选择筒管颜色
    onSelectColor(data) {
      this.spindleColor = data.name;
    },
    // 获取列表数据
    onGetTableData() {
      const that = this;
      that.tableData = [];
      that.totalRow = 0;
      getWeavingYarnBack(
        {
          standardName: this.query,
          pageNum: this.currentPage,
          pageSize: 10,
          status: 1,
          type: 2,
        },
        (res) => {
          this.totalRow = res.totalRow;
          that.tableData = res.list;
        }
      );
    },
    // 监听扫码时间
    onWatchEnter() {
      this.code = "";
      this.lastTime = "";
      this.nextTime = "";
      this.lastCode = "";
      this.nextCode = "";
      window.addEventListener("keydown", this.onClickKeydown);
    },
    // 监听事件
    onClickKeydown(e) {
      const that = this;
      if (that.show && !that.filedInputLock) {
        // that.$toast({
        //   type: "loading",
        //   message: "二维码解析中",
        //   forbidClick: true,
        //   duration: 20000,
        // });
        console.log(e);
        if (window.event) {
          // IE
          that.nextCode = e.keyCode;
        } else if (e.which) {
          // Netscape/Firefox/Opera
          that.nextCode = e.which;
        }
        if (e.which === 13) {
          if (that.code.length < 3) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
          that.$toast.clear();
          console.log("扫码结束");
          console.log(that.code.replace(/Shift/g, ""));

          let content = that.code.replace(/Shift/g, "");
          if (!that.$isJSON(content) || content.indexOf(",") == -1) {
            that.$toast.fail("二位码异常");
            return false;
          }
          let ids = eval(content);
          if (ids.toString().indexOf(",") == -1) {
            that.$toast.fail("二位码异常");
            return false;
          }
          let id = ids.split(",")[0];
          that.$refs.tabDiv.focus();
          if (!that.lock) {
            getYarnPackageFilter(id, (res) => {
              console.log(res);
              that.lock = true;
              that.yarnId = res.standardId;
              that.no = res.standardNo;
              that.name = res.colorName;
              that.standardName = res.standard;
              that.batchName = res.name;
              that.spindleMaterial = res.spindleMaterial;
              that.spindleMaterialName =
                res.spindleMaterial == 1 ? "塑料" : "纸质";
              that.spindleColor = res.spindleColor;
              that.spindleNum = res.spindleNum;
              that.grossWeight = res.grossWeight;
              that.netWeight = res.netWeight;
              that.weight = res.weight;
              that.modulus = res.modulus;
              that.stdMoistureRegain = res.stdMoistureRegain || res.modulus;
              // that.onConfirm();
            });
          } else {
            that.$toast.fail("请退出重新扫码");
          }

          that.code = "";
          that.lastCode = "";
          that.lastTime = "";
          return;
        }
        that.nextTime = new Date().getTime();
        if (!that.lastTime && !that.lastCode) {
          console.log("扫码开始。。。");
          that.code += e.key;
        }
        if (
          that.lastCode &&
          that.lastTime &&
          that.nextTime - that.lastTime > 500
        ) {
          // 当扫码前有keypress事件时,防止首字缺失
          console.log("防止首字缺失。。。");
          that.code = e.key;
        } else if (that.lastCode && that.lastTime) {
          console.log("扫码中。。。");
          that.code += e.key;
        }
        that.lastCode = that.nextCode;
        that.lastTime = that.nextTime;
      }
    },
    // 失去焦点
    onClickBlur() {
      this.filedInputLock = false;
      setTimeout(() => {
        this.top = 350 + "px";
      }, 200);
    },
    // 距离顶部距离
    onChangeTop(index) {
      setTimeout(() => {
        this.top = getFloat(this.scrollH - 90 * index, 0) + "px";
      }, 200);
    },
    // 获取重量
    onGetWeight() {
      const that = this;
      that.lock = false;
      that.grossWeight = "";
      window.removeEventListener("keydown", this.onClickKeydown);
      that.onChangeTop(1);
      // that.$toast.loading({
      //   message: "自动称重中",
      //   forbidClick: true,
      //   duration: 20000,
      //   loadingType: "spinner",
      // });
      // var serial = window.api.require("serialPort");
      // serial.examine(function (ret) {
      //   if (ret.code) {
      //     serial.openRead(
      //       {
      //         com: "/dev/ttyS3", //串口地址
      //         rate: 9600, //波特率
      //         delay: 500, //RX延时 此参数能让数据返回完整单位毫秒（具体设置大小自测）
      //         hex: false, //返回数据类型 false:text  true:hex
      //       },
      //       function (ret) {
      //         if (ret.code && ret.data) {
      //           let respon = ret.data;
      //           serial.close(function (ret) {
      //             that.$toast.clear();
      //             let res = respon.split(" ");
      //             let resultWeight = [...new Set(res)].filter(
      //               (item) => item !== ""
      //             )[0];
      //             // 关闭协议成功
      //             that.$refs.tabDiv.focus();
      //             that.grossWeight = getFloat(
      //               that.insert_flg(resultWeight.trim(), ".", 2),
      //               1
      //             );

      //             if (ret.code) {
      //               // 关闭
      //             }
      //           });
      //         }
      //       }
      //     );
      //   } else {
      //     that.$toast.clear();
      //     that.$toast.fail("协议打开失败，请手动填写重量");
      //   }
      // });
    },
    onClickSubmit() {
      this.$refs.tabDiv.focus();
    },
    // str表示原字符串变量，flg表示要插入的字符串，sn表示要插入的位置
    insert_flg(str, flg, sn) {
      var newstr = "";
      let frontStr = str.substr(0, str.length == 3 ? 1 : sn);
      let afterStr = str.substr(
        str.length == 3 ? 1 : sn,
        str.length == 3 ? sn : str.length - sn
      );
      newstr = frontStr + flg + afterStr;
      return newstr;
    },
  },
};
</script>

<style lang="scss">
.yarn-list {
  display: flex;
  flex-direction: column;
  .public-scroll {
    height: calc(100vh - 150px);
    margin: 10px;
    border: 1px solid #ddd;

    .van-cell {
      padding: 0;
      line-height: 50px;
      border-bottom: 1px solid #ddd;
      .van-button {
        color: #fff;
      }
    }
    .van-cell__title {
      flex: 0 0 85%;
      .yarn-cell {
        display: flex;
        justify-content: space-between;
        span {
          flex: 1;
          font-size: 20px;
          text-align: center;
          border-right: 1px solid #ddd;
          &:nth-child(1) {
            flex: 0 0 80px;
          }
          &:nth-child(3) {
            flex: 0 0 280px;
          }
          &:nth-child(4) {
            flex: 0 0 80px;
          }
          &:nth-child(5) {
            flex: 0 0 80px;
          }
          &:nth-child(6) {
            flex: 0 0 200px;
          }
        }
      }
    }
    .van-cell__value {
      padding-right: 20px;
      text-align: center;
      span {
        font-size: 20px;
        color: #000;
      }
    }
  }
  .van-icon-success::before {
    position: relative;
    top: 15px;
    font-size: 36px;
  }

  .yarn-list-dialog {
    width: 760px !important;
    height: 700px !important;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .van-dialog__header {
      font-size: 26px;
      color: #333333;
      padding-top: 40px;
    }
    .van-dialog__content {
      font-size: 30px;
      color: #333333;
      text-align: center;
    }
    .van-dialog__footer {
      height: 80px;
      .van-button {
        height: 100%;
        font-size: 30px;
        color: #1677ff;
      }
    }
    .van-cell__title {
      display: flex;
      flex: 0 0 150px;
      align-items: center;
      justify-content: flex-end;
    }
    .van-cell__title,
    .van-cell__value {
      span,
      .van-field__control {
        font-size: 20px;
      }
    }
    .van-cell-group {
      .van-cell {
        margin: 15px 0;
      }
    }
  }
  .yarn-btn {
    width: 700px;
    height: 100px;
    background: #1677ff;
    border-radius: 2px;
    font-size: 32px;
    color: #ffffff;
    margin: 0 auto;
    // margin-bottom: 100px;
  }
  .van-field__control {
    text-align: right;
    font-size: 18px;
  }
  .van-action-sheet {
    max-height: 90%;
  }
  .van-picker__columns {
    height: 500px !important;
  }
  .van-picker__cancel,
  .van-picker__confirm {
    font-size: 20px;
  }
  .van-picker-column__item--selected {
    font-size: 20px;
    color: #fff;
    background: #e4393c;
  }
  .van-cell--clickable {
    display: flex;
    height: 64px;
    align-items: center;
  }
  .van-field__left-icon {
    display: flex;
    align-items: center;
  }
  .van-action-sheet {
    max-height: 50% !important;
  }
}
</style>
